package com.manor.common.ktx

import androidx.viewpager2.widget.ViewPager2
import com.alibaba.fastjson.JSON
import com.blankj.utilcode.util.EncodeUtils
import com.blankj.utilcode.util.EncryptUtils
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.google.gson.Gson
import com.manor.common.Constants
import com.manor.common.utils.Gson2Util
import com.manor.common.utils.KLog
import okio.internal.commonToUtf8String

/**
 *
 * @date  2020/7/14  15:30
 * @version 1.0
 */
fun TabLayout.setBindViewPager(viewPager: ViewPager2, labels: List<String>) {

    if (labels.size != viewPager.adapter?.itemCount)
        throw Exception("The size of list and the tab count should be equal!")

    TabLayoutMediator(this, viewPager,
            TabLayoutMediator.TabConfigurationStrategy { tab, position ->
                tab.text = labels[position]
            }).attach()
}

fun TabLayout.setBindViewPager(viewPager: ViewPager2, listener: TabLayoutMediator.TabConfigurationStrategy) {
    TabLayoutMediator(this, viewPager, listener).attach()
}

fun Any.toJson(): String = Gson().toJson(this)

fun Any.toGsonArr(): ByteArray = Gson2Util.toJson(this).toByteArray()

fun Any.toFJson(): String = JSON.toJSONString(this)


inline fun <reified T> String.toBeanList(): MutableList<T> {
    try {
        return Gson().fromJson<MutableList<T>>(this, ParameterizedTypeImpl(T::class.java))
    } catch (e: Exception) {
        e.printStackTrace()
    }
    return mutableListOf()
}


inline fun <reified T> String.toBean(): T {
    return Gson().fromJson<T>(this, T::class.java)
}




inline fun String.toEncrypt(): String {
    val json = EncodeUtils.base64Encode(this.toByteArray())
    val key = EncodeUtils.base64Decode(Constants.SECRET.PubKey.toByteArray())
    val data = EncryptUtils.encryptRSA2Base64(json, key, 1024, "RSA/None/PKCS1Padding")
    return data?.commonToUtf8String()?:""
}

